//
//  XQFMDBVC.m
//  XQSqliteDemo
//
//  Created by WXQ on 2021/3/9.
//

#import "XQFMDBVC.h"
#import <Masonry/Masonry.h>
#import <XQFMDB/XQFMDB.h>
#import <FMDB/FMDB.h>
#import <XQProjectTool/XQCommonHeader.h>
#import <XQAlert/XQSystemAlert.h>
#import <MJRefresh/MJRefresh.h>
#import <XQProjectTool/UIView+XQResponse.h>
#import <XQProjectTool/UIButton+XQResponse.h>

#import "ViewControllerHeaderView.h"
#import "School.h"
#import "XQClass.h"

#define tableName_school @"school"
#define tableName_class @"class"

@interface XQFMDBVC () <UITableViewDelegate, UITableViewDataSource>

/** <#note#> */
@property (nonatomic, strong) UITableView *tableView;
/** <#note#> */
@property (nonatomic, copy) NSArray <School *> *dataArr;

/// <#note#>
@property (nonatomic, copy) NSString *cellReuseIdentifier;
/// <#note#>
@property (nonatomic, copy) NSString *headerReuseIdentifier;

@end

@implementation XQFMDBVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"FMDB";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"创建" style:UIBarButtonItemStylePlain target:self action:@selector(respondsToCreate)];
    
    [XQFMDB getDBWithResult:^(FMDatabase *db) {
        [XQFMDB createWithDB:db tableName:tableName_school autoincrementKey:@"autoincrementKey" columnDic:nil modelClass:[School class]];
        [XQFMDB createWithDB:db tableName:tableName_class autoincrementKey:@"autoincrementKey" columnDic:nil modelClass:[XQClass class]];
        
//        [FMDatabase que];
        
        
        // 删除触发器
        [db executeUpdate:@"DROP TRIGGER IF EXISTS nameUpdate"];
        
        
        // 创建一次就存在不能再次创建, 需要删除才能再次创建
        // BEFORE AFTER
        // UPDATE DELETE INSERT
        // new 是新的值, old 是老的值
        
        [XQFMDB createTriggerWithDB:db
                        triggerName:@"nameUpdate"
                   triggerOperation:@"UPDATE"
                         triggerKey:@""
                       triggerTabel:tableName_school
                      executeTiming:@"BEFORE"
                        executeCode:@"UPDATE school SET imageName = 'aaa';"];
        
        [XQFMDB queryTriggerListWithDB:db tabel:tableName_school callback:^(NSDictionary *dic) {
            NSLog(@"%@", [dic yy_modelToJSONString]);
        }];
    }];
    
    [self initTableView];
    [self getData];
    
    XQ_WS(weakSelf);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf getData];
    }];
}

- (void)initTableView {
    self.cellReuseIdentifier = @"cell";
    self.headerReuseIdentifier = @"headerReuseIdentifier";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:self.cellReuseIdentifier];
    
    [self.tableView registerClass:[ViewControllerHeaderView class] forHeaderFooterViewReuseIdentifier:self.headerReuseIdentifier];
    self.tableView.sectionHeaderHeight = 44;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)getData {
    NSMutableArray *muArr = [NSMutableArray array];
    
    [XQFMDB getDBWithResult:^(FMDatabase *db) {
        
        [XQFMDB queryWithDB:db table:tableName_school wDic:nil callback:^(FMDatabase *db, NSDictionary *dic) {
            School *sModel = [School yy_modelWithDictionary:dic];
            
            NSMutableArray *classArr = [NSMutableArray array];
            [XQFMDB queryWithDB:db table:tableName_class wDic:@{@"schoolId": sModel.sId} callback:^(FMDatabase *db, NSDictionary *dic) {
                [classArr addObject:[XQClass yy_modelWithDictionary:dic]];
            }];
            
            sModel.classArr = classArr;
            [muArr addObject:sModel];
        }];
        
    }];
    
    
    self.dataArr = muArr;
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - responds

- (void)respondsToCreate {
    [XQSystemAlert alertWithTitle:@"创建学校" message:nil contentArr:@[@"确定"] cancelText:@"取消" vc:self textFieldCount:1 textFieldBlock:^(NSUInteger index, UITextField * _Nonnull textField) {
        textField.placeholder = @"输入学校名称";
    } contentCallback:^(UIAlertController * _Nonnull alert, NSUInteger index) {
        
        NSString *name = alert.textFields.firstObject.text;
        if (!name) {
            name = @"";
        }
        
        School *model = [School new];
        model.name = name;
        [XQFMDB insertWithTable:tableName_school dic:[model yy_modelToJSONObject]];
        
        [self getData];
    } cancelCallback:nil];
}

- (void)createClassWithSchoolModel:(School *)schoolModel {
    [XQSystemAlert alertWithTitle:@"创建班级" message:nil contentArr:@[@"确定"] cancelText:@"取消" vc:self textFieldCount:1 textFieldBlock:^(NSUInteger index, UITextField * _Nonnull textField) {
        textField.placeholder = @"输入班级名称";
    } contentCallback:^(UIAlertController * _Nonnull alert, NSUInteger index) {
        
        NSString *name = alert.textFields.firstObject.text;
        if (!name) {
            name = @"";
        }
        
        XQClass *model = [XQClass new];
        model.name = name;
        model.schoolName = schoolModel.name;
        model.schoolId = schoolModel.sId;
        [XQFMDB insertWithTable:tableName_class dic:[model yy_modelToJSONObject]];
        
        [self getData];
    } cancelCallback:nil];
}

- (void)editSchoolNameWithSchoolModel:(School *)schoolModel {
    [XQSystemAlert alertWithTitle:@"修改学校名称" message:nil contentArr:@[@"确定"] cancelText:@"取消" vc:self textFieldCount:1 textFieldBlock:^(NSUInteger index, UITextField * _Nonnull textField) {
        textField.placeholder = @"输入学校名称";
    } contentCallback:^(UIAlertController * _Nonnull alert, NSUInteger index) {
        
        NSString *name = alert.textFields.firstObject.text;
        if (!name) {
            name = @"";
        }
        
        
        [XQFMDB updateWithTable:tableName_school wDic:@{@"sId": schoolModel.sId} sDic:@{@"name": name}];
        [self getData];
        
    } cancelCallback:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr[section].classArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellReuseIdentifier forIndexPath:indexPath];
    
    XQClass *cModel = self.dataArr[indexPath.section].classArr[indexPath.row];
    
    cell.textLabel.text = [NSString stringWithFormat:@"班级: %@\n学校: %@", cModel.name, cModel.schoolName];
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ViewControllerHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerReuseIdentifier];
    
    School *sModel = self.dataArr[section];
    
//    headerView.titleLab.text = sModel.name;
    headerView.titleLab.text = [NSString stringWithFormat:@"%@(点我更改名称) %@", sModel.name, sModel.imageName];
    
    XQ_WS(weakSelf);
    
    headerView.titleLab.userInteractionEnabled = YES;
    [headerView.titleLab xq_addTapWithCallback:^(UITapGestureRecognizer * _Nonnull gesture) {
        [weakSelf editSchoolNameWithSchoolModel:sModel];
    }];
    
    [headerView.addBtn xq_addEvent:UIControlEventTouchUpInside callback:^(UIButton * _Nonnull sender) {
        [weakSelf createClassWithSchoolModel:sModel];
    }];
    
    [headerView.deleteBtn xq_addEvent:UIControlEventTouchUpInside callback:^(UIButton * _Nonnull sender) {
        [XQFMDB deleteWithTable:tableName_school wDic:@{@"sId": sModel.sId}];
        [weakSelf getData];
    }];
    
    
    return headerView;
}

@end
